package cn.gson.crm.controller.graduation;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.MalformedURLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import cn.gson.crm.model.dao.BlacklistDao;
import cn.gson.crm.model.dao.InterViewDao;
import cn.gson.crm.model.dao.InterViewDataDao;
import cn.gson.crm.model.dao.StudentDao;
import cn.gson.crm.model.entity.JyBlacklist;
import cn.gson.crm.model.entity.JyInterViewData;
import cn.gson.crm.model.entity.JyInterview;
import cn.gson.crm.model.entity.Student;
import cn.gson.crm.model.mapper.InterViewMapper;
import lombok.extern.log4j.Log4j;

/**
 * 面试资料Controller
 * 
 * @author asus
 *
 */
@Controller
@RequestMapping("/interview")
@Log4j
public class InterViewController {
	/**
	 * 面试记录Dao
	 */
	@Autowired
	private InterViewDao interDao;
	/**
	 * 面试资料Dao
	 */
	@Autowired
	private InterViewDataDao interdataDao;
	/**
	 * 黑名单Dao
	 */
	@Autowired
	private BlacklistDao blackDao;
	/**
	 * 上传、下载路径
	 */
	@Value("${upload.audio}")
	private String uploadDir;
	/**
	 * 面试Mapper
	 */
	@Autowired
	private InterViewMapper interMapper;

	/**
	 * 列表显示内容查询
	 * 
	 * @param interview
	 * @param pageNum
	 * @param pageSize
	 * @param name
	 * @param type
	 * @param result
	 * @return
	 */
	@RequestMapping("/inter")
	@ResponseBody
	public Map<String, Object> inter(Map<String, Object> interview,
			@RequestParam(name = "page", defaultValue = "1") int pageNum,
			@RequestParam(name = "rows", defaultValue = "20") int pageSize,
			@RequestParam(name = "name", required = false) String name,
			@RequestParam(name = "type", required = false) String type,
			@RequestParam(name = "result", required = false) String result,
			@RequestParam(name = "id", required = false) String id,
			@RequestParam(name = "company", required = false) String company,
			@RequestParam(name = "start_time", required = false) String startTime,
			@RequestParam(name = "end_time", required = false) String endTime) {
		// 查询数据
		PageHelper.startPage(pageNum, pageSize);
		interview.put("name", name);
		interview.put("type", type);
		interview.put("result", result);
		interview.put("id", id);
		interview.put("company", company);
		interview.put("start_time", startTime);
		interview.put("end_time", endTime);
		List<JyInterview> pageData = interMapper.interViewList(interview);
		PageInfo<JyInterview> info = new PageInfo<>(pageData);
		// 组装返回结果
		Map<String, Object> obj = new HashMap<String, Object>(16);
		obj.put("total", info.getTotal());
		obj.put("rows", info.getList());
		return obj;
	}

	/**
	 * 打开添加或编辑窗口
	 * 
	 * @param model
	 * @return
	 */
	@GetMapping({ "addinter", "addinter/{id}" })
	public String addinter(@PathVariable(name = "id", required = false) Long id, Model model) {
		if (id != null) {
			JyInterViewData jyd = interDao.findOne(id).getInterData();
			Map<String, Object> inter = interMapper.selectInterOne(id, jyd);
			System.out.println(inter);
			if (inter != null) {
				System.out.println(id);
				model.addAttribute("inter", inter);
			}
		}
		return "base";
	}

	/**
	 * 虚拟删除方法体
	 * 
	 * @param id
	 * @return
	 */
	@GetMapping("delete/{id}")
	@ResponseBody
	@Transactional(rollbackFor = Exception.class)
	public Map<String, Object> delete(@PathVariable("id") Long id) {
		Map<String, Object> obj = new HashMap<String, Object>(16);
		obj.put("success", false);
		JyInterview jy;
		JyInterViewData jyd;
		if (id != null && (jy = interDao.findOne(id)) != null) {
			if (jy.getInterData() != null) {
				if ((jyd = interdataDao.findOne(jy.getInterData().getId())) != null) {
					File fileDelete = new File(System.getProperty("user.dir") + uploadDir,
							jy.getInterData().getContent());
					fileDelete.delete();
					interMapper.deleteInterViewData(jyd.getId());
				}
			}
			interMapper.deleteInterView(jy.getId());
			obj.put("success", true);
		} else {
			obj.put("message", "此记录不存在！");
		}
		return obj;
	}

	/**
	 * 添加、编辑面试记录的方法体
	 * 
	 * @param type
	 * @param jy
	 * @param br
	 * @param modtype
	 * @param file
	 * @return
	 */
	@PostMapping("/save")
	@ResponseBody
	@Transactional(rollbackFor = Exception.class)
	public Map<String, Object> save(@RequestParam(name = "type", required = false) String type, @Valid JyInterview jy,
			BindingResult br, @RequestParam(defaultValue = "inter", required = false) String modtype,
			@RequestParam(name = "content", required = false) MultipartFile file) {
		Map<String, Object> obj = new HashMap<String, Object>(16);
		try {
			obj.put("success", false);
			if (br.hasErrors()) {
				obj.put("message", "校验失败！");
				obj.put("erros", br.getFieldErrors());
				return obj;
			} else {
				
				if (jy.getStudent() == null) {
					obj.put("message", "请选择正确的学员!");
					return obj;
				}
				if (file.getOriginalFilename() != null && !"".equals(file.getOriginalFilename())) {
					int maxSize = 100 * 1024 * 1024;
					if (file.getSize() > maxSize) {
						obj.put("message", "文件大小超过100MB!");
					}
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
					String dateDir = sdf.format(new Date());
					// 获取文件后缀名
					String ext = FilenameUtils.getExtension(file.getOriginalFilename());
					String newFileName = UUID.randomUUID().toString() + "." + ext;
					String pic = "图片";
					String audio = "音频";
					if (pic.equals(type)) {
						modtype = "images";
					} else if (audio.equals(type)) {
						modtype = "audio";
					}
					String filePath = String.format("%s/%s/%s", uploadDir, modtype, dateDir);
					File fileDir = new File(System.getProperty("user.dir") + filePath);
					if (!fileDir.exists()) {
						// 如果目录不存在，则创建出来
						fileDir.mkdirs();
					}
					JyInterViewData ivd = new JyInterViewData();
					ivd.setDelete(true);
					ivd.setType(type);
					ivd.setModeType(modtype);
					ivd.setMediaName(file.getOriginalFilename());
					ivd.setContent(String.format("%s/%s/%s", modtype, dateDir, newFileName));
					ivd.setSize(file.getSize());
					ivd.setSuffix(ext);
					interdataDao.save(ivd);
					jy.setInterData(ivd);
					file.transferTo(new File(fileDir, newFileName));
				}
				int y = Integer.parseInt(jy.getIvtime().substring(0, 4));
				int m = Integer.parseInt(jy.getIvtime().substring(5, 7));
				int d = Integer.parseInt(jy.getIvtime().substring(8, 10));
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				String date = sdf.format(new Date());
				int y1 = Integer.parseInt(date.substring(0, 4));
				int m1 = Integer.parseInt(date.substring(5, 7));
				int d1 = Integer.parseInt(date.substring(8, 10));
				if(jy.getId()==null && (y>y1 || m>m1 || d>d1)) {
					jy.setResult(2);
				}
				if(jy.getId() != null) {
					JyInterview ji=interDao.findOne(jy.getId());
					if(jy.getInterData().getContent() == null) {
						jy.setInterData(ji.getInterData());
					}
					jy.setMessage(ji.getMessage());
					jy.setPlan(ji.getPlan());
				}
				jy.setDelete(true);
				interDao.save(jy);
				obj.put("success", true);
				return obj;
			}
		} catch (Exception e) {
			log.error("添加失败！", e);
			obj.put("message", "添加失败！");
		}
		return obj;
	}

	@GetMapping("/save/**")
	@ResponseBody
	public void preview(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String path = request.getServletPath();
		log.info(path);
		String p = System.getProperty("user.dir")+uploadDir;
		String rep = "\\\\";
		String p1 = p.replaceAll(rep, "/");
		path = path.replaceFirst("/interview/save/", p1);
		ServletOutputStream os = response.getOutputStream();
		File f = new File(path);
		log.info(f);
		if (!f.exists()) {
			// 附件不存在的时候，直接返回404
			response.sendError(404);
			return;
		}
		// 创建一个输入流
		FileInputStream fis = new FileInputStream(f);
		// 每次读取的字节数
		byte[] b = new byte[2048];
		// 每次实际读取到的字节长度
		int len = 0;
		while ((len = fis.read(b)) > 0) {
			// 进入循环，表示读取到了字节
			// 读到多少，就写出多少
			os.write(b, 0, len);
		}

		fis.close();
	}

	
	/**
	 * 下载
	 * 
	 * @param request
	 * @param response
	 * @param attId
	 * @throws IOException
	 */
	@GetMapping("/download/{attId}")
	@ResponseBody
	public void download(HttpServletRequest request, HttpServletResponse response, @PathVariable("attId") Long attId)
			throws IOException {
		// 根据id获取附件信息
		JyInterViewData att = interdataDao.findOne(attId);

		if (att == null) {
			// 附件不存在的时候，直接返回404
			response.sendError(404);
			return;
		}

		// 设置下载响应头信息
		response.setContentLengthLong(att.getSize());
		response.setContentType(att.getModeType());
		// 设置附件存储的默认文件名
		response.setHeader("Content-Disposition",
				"interview;filename=" + new String(att.getMediaName().getBytes("UTF-8"), "ISO8859-1"));
		String path = System.getProperty("user.dir") + uploadDir + att.getContent();
		ServletOutputStream os = response.getOutputStream();

		// 创建一个输入流
		FileInputStream fis = new FileInputStream(path);
		// 每次读取的字节数
		byte[] b = new byte[2048];
		// 每次实际读取到的字节长度
		int len = 0;
		while ((len = fis.read(b)) > 0) {
			// 进入循环，表示读取到了字节
			// 读到多少，就写出多少
			os.write(b, 0, len);
		}

		fis.close();
	}

	/**
	 * 播放音频文件
	 * 
	 * @param id
	 * @param model
	 * @return
	 * @throws MalformedURLException
	 */
	@RequestMapping("player/{id}")
	public String player(@PathVariable("id") Long id, Model model) throws MalformedURLException {
		JyInterViewData jy = interdataDao.findOne(id);
		String path = "public/" + jy.getContent();
		File file = new File(path);
		String filepath = System.getProperty("user.dir") + uploadDir + jy.getContent();
		File file1 = new File(filepath);
		if (!file1.exists()) {
			model.addAttribute("error", "该音频文件不存在！");
		}
		model.addAttribute("madio", file);
		return "player";
	}

	/**
	 * 显示预案
	 * 
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping("plans/{id}")
	public String plans(@PathVariable("id") Long id, Model model) {
		JyInterview jy = interDao.findOne(id);
		String plan = "";
		plan = jy.getPlan();
		model.addAttribute("plan", plan);
		return "plans";
	}

	/**
	 * 显示留言
	 * 
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping("leavmess/{id}")
	public String leavmess(@PathVariable("id") Long id, Model model) {
		JyInterview jy = interDao.findOne(id);
		String mess = jy.getMessage();
		model.addAttribute("mess", mess);
		return "leavmess";
	}

	/**
	 * 前台显示留言
	 * 
	 * @param id
	 * @param model
	 * @return
	 */
	@RequestMapping("leavm/{id}")
	public String leavmess1(@PathVariable("id") Long id, Model model) {
		JyInterview jy = interDao.findOne(id);
		String mess = jy.getMessage();
		model.addAttribute("mess", mess);
		return "leavm";
	}

	/**
	 * 添加教员留言
	 * 
	 * @param id
	 * @return
	 */
	@PostMapping("getmess/{id}")
	@ResponseBody
	@Transactional(rollbackFor = Exception.class)
	public Map<String, Object> getmess(@PathVariable("id") Long id,
			@RequestParam(name = "mess", required = false) String mess) {
		Map<String, Object> obj = new HashMap<String, Object>(16);
		obj.put("success", false);
		JyInterview jy = new JyInterview();
		if (id != null && (jy = interDao.findOne(id)) != null) {
			interMapper.saveMess(id, mess);
			obj.put("success", true);
		} else {
			obj.put("message", "此记录不存在！");
		}
		return obj;
	}

	/**
	 * 添加预案
	 * 
	 * @param id
	 * @return
	 */
	@PostMapping("getplan/{id}")
	@ResponseBody
	@Transactional(rollbackFor = Exception.class)
	public Map<String, Object> getplan(@PathVariable("id") Long id,
			@RequestParam(name = "plan", required = false) String plan) {
		Map<String, Object> obj = new HashMap<String, Object>(16);
		obj.put("success", false);
		JyInterview jy = new JyInterview();
		if (id != null && (jy = interDao.findOne(id)) != null) {
			interMapper.savePlan(id, plan);
			obj.put("success", true);
		} else {
			obj.put("message", "此记录不存在！");
		}
		return obj;
	}

	/**
	 * 我的记录
	 * 
	 * @param id
	 * @return
	 */
	@GetMapping("mine/{id}")
	@ResponseBody
	public JyInterview messofmine(@PathVariable("id") Long id) {
		JyInterview jy = new JyInterview();
		jy = interDao.findOne(id);
		return jy;
	}

	/**
	 * 前台添加面试记录
	 * 
	 * @param jy
	 * @param br
	 * @return
	 */
	@PostMapping("/recepsave")
	@ResponseBody
	@Transactional(rollbackFor = Exception.class)
	public Map<String, Object> recepSave(@Valid JyInterview jy, BindingResult br) {
		Map<String, Object> obj = new HashMap<String, Object>(16);
		obj.put("success", false);
		if (br.hasErrors()) {
			obj.put("message", "校验失败！");
			obj.put("erros", br.getFieldErrors());
		} else {
			int y = Integer.parseInt(jy.getIvtime().substring(0, 4));
			int m = Integer.parseInt(jy.getIvtime().substring(5, 7));
			int d = Integer.parseInt(jy.getIvtime().substring(8, 10));
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			String date = sdf.format(new Date());
			int y1 = Integer.parseInt(date.substring(0, 4));
			int m1 = Integer.parseInt(date.substring(5, 7));
			int d1 = Integer.parseInt(date.substring(8, 10));
			if(jy.getId()==null && (y>y1 || m>m1 || d>d1)) {
				jy.setResult(2);
			}
			jy.setDelete(true);
			interDao.save(jy);
			obj.put("success", true);
		}
		return obj;
	}
	
	/**
	 * 添加黑名单公司
	 * 
	 * @param jy
	 * @param br
	 * @return
	 */
	@PostMapping("/saveblack")
	@ResponseBody
	@Transactional(rollbackFor = Exception.class)
	public Map<String, Object> saveBlack(@Valid JyBlacklist jy, BindingResult br) {
		Map<String, Object> obj = new HashMap<String, Object>(16);
		obj.put("success", false);
		if (br.hasErrors()) {
			obj.put("message", "校验失败！");
			obj.put("erros", br.getFieldErrors());
		} else {
			blackDao.save(jy);
			obj.put("success", true);
		}
		return obj;
	}

	/**
	 * 显示前台添加记录页面
	 * @return
	 */
	@RequestMapping("recepadd")
	public String add() {
		return "recepsave";
	}
	/**
	 * 显示添加黑名单公司
	 * @return
	 */
	@RequestMapping("addblack")
	public String addblack() {
		return "addblack";
	}

	@RequestMapping("/black")
	@ResponseBody
	public Map<String, Object> black(JyBlacklist bl, @RequestParam(name = "page", defaultValue = "1") int pageNum,
			@RequestParam(name = "rows", defaultValue = "20") int pageSize) {
		// 查询数据
		PageHelper.startPage(pageNum, pageSize);
		List<JyBlacklist> pageData = interMapper.selectBlackList(bl);

		PageInfo<JyBlacklist> info = new PageInfo<>(pageData);
		// 组装返回结果
		Map<String, Object> obj = new HashMap<String, Object>();
		obj.put("total", info.getTotal());
		obj.put("rows", info.getList());
		return obj;
	}
}
